import { FC, useEffect, useState } from "react";
import idbService from '../../indexed-db/idb';
import { Customer } from "../../indexed-db/idb.type";
import './Customer.css';

const CustomerContainer: FC = () => {
    const [customers, setCustomers] = useState<Customer[]>([]);
    const [name, setName] = useState<string>('');
    const [email, setEmail] = useState<string>('');
    const [isLoading, setIsLoading] = useState<boolean>(true);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        const initDBAndLoadData = async () => {
            try {
                await idbService.open();
                const data = await idbService.getAllCustomers();
                setCustomers(data);
                setIsLoading(false);
            } catch (err) {
                setError(`Initializing IndexedDB failed: ${err instanceof Error ? err.message : 'Unknown error'}`);
            }
        };
        initDBAndLoadData();

        return () => {
            idbService.close();
        };
    }, []);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!name.trim() || !email.trim()) return;
        const newCustomerData: Omit<Customer, 'id'> = { name, email };

        try {
            const addedCustomer = await idbService.addCustomer(newCustomerData);
            setCustomers(prevCustomers => [...prevCustomers, addedCustomer]);
            // 清空表单
            setName('');
            setEmail('');
            if (error) setError(null); // 清除之前的错误
        } catch (err) {
            setError('添加客户失败: ' + (err instanceof Error ? err.message : String(err)));
            // 短暂显示错误后清除
            setTimeout(() => setError(null), 3000);
        }


    };

    const handleDelete = async (id: number) => {
        try {
            await idbService.deleteCustoemrById(id);
            setCustomers(prevCustomers => prevCustomers.filter(customer => customer.id !== id));
            if (error) setError(null);
        } catch (err) {
            setError('删除客户失败: ' + (err instanceof Error ? err.message : String(err)));
            setTimeout(() => setError(null), 3000);
        }
    };
    return (
        <div className="App">
            <header className="App-header">
                <h1>Customers</h1>
                <div>{isLoading ? 'Loading...' : 'Ready'}</div>
            </header>
            <main className="App-main">
                {error && <div className="error-message">{error}</div>}

                <section className="add-customer-form">
                    <h2>Add new customer</h2>
                    <form onSubmit={handleSubmit}>
                        <input
                            type="text"
                            placeholder="姓名"
                            value={name}
                            onChange={(e: React.ChangeEvent<HTMLInputElement>) => setName(e.target.value)}
                            required
                        />
                        <input
                            type="email"
                            placeholder="邮箱"
                            value={email}
                            onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEmail(e.target.value)}
                            required
                        />
                        <button type="submit">Add</button>
                    </form>
                </section>

                <section className="customer-list">
                    <h2>客户列表</h2>
                    {customers.length === 0 ? (
                        <p>No customer data available. Please add a new customer.</p>
                    ) : (
                        <ul>
                            {customers.map((customer) => (
                                <li key={customer.id}>
                                    <div>
                                        <strong>{customer.name}</strong> ({customer.email})
                                    </div>
                                    <button onClick={() => handleDelete(customer.id!)}>Delete</button>
                                </li>
                            ))}
                        </ul>
                    )}
                </section>
            </main>
        </div>
    );
};

export default CustomerContainer;